package com.tqsa.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tqsa.common.convention.exception.ClientException;
import com.tqsa.common.convention.result.Result;
import com.tqsa.common.convention.result.Results;
import com.tqsa.common.enums.UserErrorCodeEnum;
import com.tqsa.dto.UserRegisterDTO;
import com.tqsa.dto.UserUpdateDTO;
import com.tqsa.entity.UserDO;
import com.tqsa.vo.UserVO;
import com.tqsa.web.dao.mapper.UserMapper;
import com.tqsa.web.service.UserService;
import org.omg.CORBA.UserException;
import org.springframework.stereotype.Service;

/**
 * @author tqsa01
 * @description 针对表【users】的数据库操作Service实现
 * @createDate 2024-03-26 09:14:47
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO>
        implements UserService {

    @Override
    public Result<UserVO> getUserByUserName (String username) {
        UserDO userDO = baseMapper.selectOne (Wrappers.lambdaQuery (UserDO.class).eq (UserDO :: getUsername, username));
        if (userDO == null) {
            throw new ClientException (UserErrorCodeEnum.USER_NULL);
        }
        UserVO ret = BeanUtil.toBean (userDO, UserVO.class);
        return Results.success (ret);
    }

    @Override
    public Result<Void> register (UserRegisterDTO userRegisterDTO) {
        if (userRegisterDTO == null) {
            throw new ClientException ("");
        }
        UserDO userDO = BeanUtil.toBean (userRegisterDTO, UserDO.class);
        int insert = baseMapper.insert (userDO);
        if (insert < 1) {
            throw new ClientException (UserErrorCodeEnum.USER_SAVE_ERROR);
        }
        return Results.success ();
    }

    @Override
    public Result<Void> deleteUserByUsername (String username) {
        int delete = baseMapper.delete (Wrappers.lambdaQuery (UserDO.class).eq (UserDO :: getUsername, username));
        if(delete<1){
            throw new ClientException (UserErrorCodeEnum.USER_DELETE_ERROR);
        }
        return Results.success ();
    }

    @Override
    public Result<Void> updateUserByUsername (UserUpdateDTO userUpdateDTO) {
        if (userUpdateDTO== null) {
            throw new ClientException ("");
        }
        UserDO userDO = BeanUtil.toBean (userUpdateDTO, UserDO.class);
        int update = baseMapper.update (userDO,Wrappers.lambdaUpdate (UserDO.class).eq (UserDO::getUsername,userUpdateDTO.getUsername ()));
        if (update < 1) {
            throw new ClientException (UserErrorCodeEnum.USER_UPDATE_ERROR);
        }
        return Results.success ();
    }
}




